package ist.utl.pt.smartfleet.stationterminal;



import ist.utl.pt.smartfleet.stationterminal.rest.webservice.station.StationWebServiceUtil;
import ist.utl.pt.smartfleet.stationterminal.rest.webservice.traveller.TravellerWebServiceUtil;
import ist.utl.pt.smartfleet.stationterminal.station.Station;
import ist.utl.pt.smartfleet.stationterminal.util.constants.Constants;
import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

public class StationTerminal extends Activity {
	
	private RegisterValues reg_values = new RegisterValues();
	private static final int CHECKIN_ID = 0;
	private static final int MAPA_ID = 1;
	private static final int HELP_ID = 2;
	private static final int ACTIVITY_CREATE = 0;
	
	static final int Near_Entity = 1;
	static final int boardingPassagers = 2;
	
	//Dados iniciais   <-> veem da classe Initial
	private int _id;
	private Intent inte;
	private Bundle _initBundle;
	
	private Station station;
	
	//Base de dados
	private BDAdapter mDbHelper;
	
	private int count = 0;
	private String idTraveller = null;

	boolean init = false;
	boolean initDone = false;
	
	private Boolean SimIsBound = false;
	Messenger mBoundSim;
	
	Dialog destination_dialog;
	
	/*
	 * Possible Station states:
	 * 	- on
	 * 	- off
	 * 	- full
	 * 
	 * Possible Traveller states:
	 * 
	 *  - atStation
	 *  - atTrip
	 *   
	 *   Possible Vehicle states:
	 *   
	 *  - atStation
	 *  - atCharging
	 *  - Tripin
	 */
	private String state = "on";
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GridView gridview = (GridView) findViewById(R.id.gridview);
		gridview.setAdapter(new ImageAdapter(this));
		
		
		/** Initiate activity to collect id and port and location **/
		inte = new Intent(this, Initial.class);
        startActivityForResult(inte, 1);
        
        /** Create database **/
        
        mDbHelper = new BDAdapter(this);
		

		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				switch (position) {
				case CHECKIN_ID:
					abrirCheckIn();
					break;
				case MAPA_ID:
					abrirConfig();
					break;
				case HELP_ID:
					abrirHelp();
					break;
				}
			}
		});
		
	}
   
    
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
        	//Toast.makeText(StationTerminal.this, "Test: ", Toast.LENGTH_SHORT).show();
        	mBoundSim = new Messenger(service);
            Message msg = Message.obtain(null, SimService.Register_Station, _id, 0, reg_values);
            msg.replyTo = mMessenger;
            try {
				mBoundSim.send(msg);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 

            SimIsBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
        	mBoundSim = null;
        	SimIsBound = false;
        }
    };		    
		    
	
	    void doBindService() {
        
	    	bindService(new Intent(this, SimService.class), mConnection, Context.BIND_AUTO_CREATE);

	        initDone = true;
	    }

	    void doUnbindService() {
	    	if (SimIsBound) {
  		      	// Detach our existing connection.
   		         unbindService(mConnection);
	    	}
	    	
  	  }
	    
	    /** Teste handler **/
	    
	    class IncomingHandler extends Handler {
	        @Override
	        public void handleMessage(Message msg) {
	            switch (msg.what) {
	                case boardingPassagers:
	                	createDialog((String) msg.obj);
	             	   	break;
	                default:
	                	super.handleMessage(msg);
	            }
	        }
	    }
	    
	    
	    final Messenger mMessenger = new Messenger(new IncomingHandler());
	    
	    @Override
	    protected void onStart() {
	        super.onStart();
	        
	        if(init){
	        	
	        	//REGISTO NO SERVIDOR
	        	station = StationWebServiceUtil.getStationInfo(""+_id); // aqui j� tem a informacao que vem do server
    	 		StationWebServiceUtil.updateStationState(this._id, Constants.STATION_STATE_ON);// actualiza o estado da station no central server
    			reg_values.setLongitude(station.getLocation().getLongitude());
    			reg_values.setLatitude(station.getLocation().getLatitude());
	            reg_values.set_StationName(station.getLocation().getName()); 
    			
	        	/** REGISTO NO SIMULADOR **/
	            doBindService();
	            

		        initDone = true;
	        	
	        	/** Open database **/
	        	mDbHelper.open(_id);
	          
	        	String ide = mDbHelper.createLocation(reg_values.get_StationName(), reg_values.getLatitude(), reg_values.getLongitude());
	        	mDbHelper.initiateStation(_id, state, ide);
	        	
	        	Toast.makeText(this, "Station Initialized on SERVER", Toast.LENGTH_SHORT).show();
	        	Toast.makeText(this, "Station Initialized on SIMULATOR", Toast.LENGTH_SHORT).show();
	        	
	        	mDbHelper.pause();
	        	
	        }
	        
	        
	        init = false;
	        
	    }
	    
	    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
	    	super.onActivityResult(requestCode, resultCode, intent);
	    	if (intent != null){
	        
	    		if (intent.getFlags() == 1){ //CRIA UM NOVO TRAVELLER
	    			Bundle extras = intent.getExtras();
	        	
	    			String nome = extras.getString("nome");
	    			String morada = extras.getString("morada");
	    			int nrPassageiros = extras.getInt("nrPassageiros");
	    			Double la = extras.getDouble("latitude");
	    			Double lo = extras.getDouble("longitude");
	    			Long tempo = System.currentTimeMillis();
	    			
	    			la = 38.7598394;
	    			
	    			lo = -9.2372704;
	        	
	    			mDbHelper.open(_id);
	    			
	    			String idLocal = mDbHelper.createLocation(morada, la, lo);
	    			count++;
	    			idTraveller = _id+""+count;
	    			mDbHelper.createTraveller(idTraveller, nome, nrPassageiros, idLocal, tempo, _id);
	    			mDbHelper.pause();  
	    			
	    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, nome,morada, "onStation", nrPassageiros+"", tempo+"", +reg_values.get_id()+"", la+"", lo+"");
	    			
	    			Toast.makeText(StationTerminal.this, "Passageiro "+nome+", foi registado com sucesso" , Toast.LENGTH_LONG).show();
	    			 
	    	/*		if (_id == 1){
	    			idTraveller = _id+""+count;
	    			tempo = System.currentTimeMillis();
	    			mDbHelper.open(_id);
	    			String idLocal = mDbHelper.createLocation("Amadora",  38.7598394, -9.2372704);
	    			mDbHelper.createTraveller(idTraveller, "João", 3, idLocal, tempo, _id);
	    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "João","Amadora", "onStation", 3+"", tempo+"",reg_values.get_id()+"",  +38.7598394+"", -9.2372704+"");
	    			count++;
	    			idTraveller = _id+""+count;
	    			idLocal = mDbHelper.createLocation("Lumiar", 38.7661304, -9.1598511);
	    			mDbHelper.createTraveller(idTraveller, "Antoine", 1, idLocal, tempo, _id);
	    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Antoine","Lumiar", "onStation", 1+"", tempo+"",reg_values.get_id()+"",  +38.7661304+"", -9.1598511+"");
	    			count++;
	    			idTraveller = _id+""+count;
	    			idLocal = mDbHelper.createLocation("H.Santa Maria", 38.7479251, -9.1610527);
	    			mDbHelper.createTraveller(idTraveller, "Ana", 2, idLocal, tempo, _id);
	    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Pichas","Lumiar", "onStation", 2+"", tempo+"",reg_values.get_id()+"",  +38.7479251+"", -9.1610527+"");
	    			count++;
	    			idTraveller = _id+""+count;
	    			idLocal = mDbHelper.createLocation("Parq da Bela vista", 38.7467201, -9.1246605);
	    			mDbHelper.createTraveller(idTraveller, "Zaite", 4, idLocal, tempo, _id);
	    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Zaite","Parq da Bela vista", "onStation", 4+"", tempo+"",reg_values.get_id()+"",  +38.7467201+"", -9.1246605+"");
	    			
	    		//	mDbHelper.createStation(2, 38.736762, -9.13831, "IST-Alameda");
	    		//	mDbHelper.createStation(3, 38.736854, -9.302748, "IST-Taguspark");
	    			
	    			mDbHelper.pause();
	    			
	    			Toast.makeText(StationTerminal.this, "BASE DE DADOS POPULADA" , Toast.LENGTH_LONG).show();
	    			}
	    			
	    			if (_id == 2){
	    				idTraveller = _id+""+count;
		    			tempo = System.currentTimeMillis();
		    			mDbHelper.open(_id);
		    			
		    			String idLocal = mDbHelper.createLocation("Portela", 38.7823239, -9.1100693);
		    			mDbHelper.createTraveller(idTraveller, "Jousé", 2, idLocal, tempo, _id);
		    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Jousé","Portela", "onStation", 2+"", tempo+"",reg_values.get_id()+"",  +38.7823239+"", -9.1100693+"");
		    			count++;
		    			idTraveller = _id+""+count;
		    			idLocal = mDbHelper.createLocation("Alfragide", 38.7333307, -9.2185593);
		    			mDbHelper.createTraveller(idTraveller, "Zé Camolas", 3, idLocal, tempo, _id);
		    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Zé Camolas","Alfragide", "onStation", 3+"", tempo+"",reg_values.get_id()+"",  +38.7333307+"", -9.2185593+"");
		    			count++;
		    			idTraveller = _id+""+count;
		    			idLocal = mDbHelper.createLocation("Damaia", 38.7467201, -9.2139244); 
		    			mDbHelper.createTraveller(idTraveller, "Jarbas", 2, idLocal, tempo, _id);
		    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Jarbas","Damaia", "onStation", 2+"", tempo+"",reg_values.get_id()+"",  +38.7467201+"", -9.2139244+"");
		    			count++;
		    			idTraveller = _id+""+count;
		    			idLocal = mDbHelper.createLocation("Monsanto", 38.7279742, -9.1830254);
		    			mDbHelper.createTraveller(idTraveller, "Javardo", 1, idLocal, tempo, _id);
		    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Javardo","Monsanto", "onStation", 1+"", tempo+"",reg_values.get_id()+"",  +38.7279742+"", -9.1830254+"");
	    				
		    		//	mDbHelper.createStation(1, 38.771149, -9.128523, "Aeroporto Portela");
		    		//	mDbHelper.createStation(3, 38.736854, -9.302748, "IST-Taguspark");
		    			
		    			mDbHelper.pause();
		    			
		    			Toast.makeText(StationTerminal.this, "BASE DE DADOS POPULADA" , Toast.LENGTH_LONG).show();
		    			}
	    			if (_id == 3){
	    				idTraveller = _id+""+count;
		    			tempo = System.currentTimeMillis();
		    			mDbHelper.open(_id);
	    				
		    			String idLocal = mDbHelper.createLocation("Bairro Alto", 38.7112325, -9.1534996);
		    			mDbHelper.createTraveller(idTraveller, "Cortes", 1, idLocal, tempo, _id);
		    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Cortes","Bairro Alto", "onStation", 1+"", tempo+"",reg_values.get_id()+"",  +38.7112325+"", -9.1534996+"");
		    			count++;
		    			idTraveller = _id+""+count;
		    			idLocal = mDbHelper.createLocation("Almada", 38.6801497, -9.1552162);
		    			mDbHelper.createTraveller(idTraveller, "Dread", 3, idLocal, tempo, _id);
		    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Preto","Almada", "onStation", 3+"", tempo+"",reg_values.get_id()+"",  +38.6801497+"", -9.1552162+"");
		    			count++;
		    			idTraveller = _id+""+count;
		    			idLocal = mDbHelper.createLocation("Oceanário", 38.7635873, -9.0937614);
		    			mDbHelper.createTraveller(idTraveller, "Turista", 2, idLocal, tempo, _id);
		    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Turista","Oceanário", "onStation", 3+"", tempo+"",reg_values.get_id()+"",  +38.7635873+"", -9.0937614+"");
		    			count++;
		    			idTraveller = _id+""+count;
		    			idLocal = mDbHelper.createLocation("Chelas", 38.7464858, -9.1119790);
		    			mDbHelper.createTraveller(idTraveller, "Russe", 1, idLocal, tempo, _id);
		    			TravellerWebServiceUtil.saveTravellerCheckedIn(idTraveller, "Russe","Chelas", "onStation", 3+"", tempo+"",reg_values.get_id()+"",  +38.7464858+"", -9.1119790+"");
		    			
		    		//	mDbHelper.createStation(1, 38.771149, -9.128523, "Aeroporto Portela");
		    		//	mDbHelper.createStation(2, 38.736762, -9.13831, "IST-Alameda");
		    			
		    			mDbHelper.pause();
		    			
		    			Toast.makeText(StationTerminal.this, "BASE DE DADOS POPULADA" , Toast.LENGTH_LONG).show();
		    			} */
	    			
	    			//	abrirConfig();
	        	
	    			//Criar um novo evento para mandar po server o novo pedido!
	    			
	    		} else if (intent.getFlags() == 2){ //INITIAL
	    			Bundle extras = intent.getExtras();
	        	
	    			_id = Integer.parseInt(extras.getString("id"));
	    			reg_values.set_id(_id);
	    			reg_values.set_netport(Integer.parseInt(extras.getString("netport")));
	    			reg_values.set_emulport(Integer.parseInt(extras.getString("emulport")));
	    			//reg_values.set_ipLocal(extras.getString("ip"));
	    			reg_values.set_sim_addr(extras.getString("sim_addr"));
	    			reg_values.set_sim_port(Integer.parseInt(extras.getString("sim_port")));
	    		//	reg_values.set_central_address(extras.getString("central_addr"));
	    		//	reg_values.set_central_port(Integer.parseInt(extras.getString("central_port")));
	    			
	    			init = true;
	    		}
	    	}

	    }
	    
	    @Override
	    protected void onDestroy() {
	        super.onDestroy();
	        
	        mDbHelper.open(_id);
	        mDbHelper.close();
	        
	        if (initDone){
	        	try {
	        	
	        		mBoundSim.send(Message.obtain(null, SimService.Unregister_Station, _id, 0));
				
	        	} catch (RemoteException e) {
	        		// TODO Auto-generated catch block
	        		e.printStackTrace();
	        	}
	        	
	        	doUnbindService();
			
	        }
	        

	    	
	    }
	    
	    private void createDialog(String in){
	    	
	    	Toast.makeText(this, in, Toast.LENGTH_LONG).show();
	    	
	    	
	    }
	    
	    

	    protected void abrirConfig() {
	    	try {
				mBoundSim.send(Message.obtain(null, 4, _id, 0));
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	
	    }
	
	    protected void abrirCheckIn() {
	    	Intent i = new Intent(this, CheckIn.class);
	    	startActivityForResult(i, ACTIVITY_CREATE);
		}
	    
	    protected void abrirHelp() {
	    	mDbHelper.open(_id);
	    	mDbHelper.printDBVehicles();
	    	mDbHelper.printDBStation();
	    	mDbHelper.printDBLocations();
	    	mDbHelper.printDBTravellers();
	    	mDbHelper.pause();
	    	
		}
	    
	    public Bundle getInitBundle() {
			return _initBundle;
		}

		public void setInitBundle(Bundle initBundle) {
			_initBundle = initBundle;
		}
		
		
		
}